/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.mzk.oai.metadataRepository.harvest;

import cz.mzk.oai.metadataRepository.tools.CannotReadDirectoryException;
import cz.mzk.oai.metadataRepository.metadata.DateStamp;
import cz.mzk.oai.metadataRepository.repository.MetadataBase;
import cz.mzk.oai.metadataRepository.tools.FileTools;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Represents directory containing several export files
 * @author Martin Rehanek, Martin.Rehanek@gmail.com
 */
public class AlephExports {

    private File exportDir;
    private MetadataBase base;
    private List<AlephExport> exports;

    public AlephExports(File exportDir, MetadataBase base) throws CannotReadDirectoryException {
        this.exportDir = exportDir;
        this.base = base;
        if (!exportDir.isDirectory()) {
            throw new IllegalArgumentException(exportDir.getAbsoluteFile() + " is not directory");
        }

        List<String> allFileNames = FileTools.readFilenames(exportDir);
        exports = new ArrayList<AlephExport>(allFileNames.size());
        for (String fileName : allFileNames) {
            File file = new File(exportDir.getAbsoluteFile() + File.separator + fileName);
            if (file.getTotalSpace() != 0) {//because if export is not created, the emtpy file is created by the script anyway
                try {
                    AlephExport export = new AlephExport(file, base);
                    exports.add(export);
                } catch (IncorrectFilenameException ex) {
                    System.err.println("Incorrect filename " + file.getName() + "for base " + base.toString());
                    //Logger.getLogger(AlephExports.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }

    /**
     * Returns list of exports created between from and until
     * @param from
     * @param until
     * @return
     */
    public List<AlephExport> getSortedExports(DateStamp from, DateStamp until) {
        List<AlephExport> result = new ArrayList<AlephExport>();
        for (AlephExport export : exports) {
            if ((export.getDateStamp().compareTo(from) >= 0)
                    && (export.getDateStamp().compareTo(until) <= 0)) {
                result.add(export);
            }
        }
        Collections.sort(result);
        return result;
    }

    public File getExportDir() {
        return exportDir;
    }

    public MetadataBase getBase() {
        return base;
    }
}
